package cn.tedu;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Main {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("服务已经启动 端口是 8888...");

        while (true) {
            try (Socket socket = serverSocket.accept();
                 BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                 BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))) {

                String requestLine = reader.readLine();
                System.out.println("Received request: " + requestLine);

                if (requestLine != null && requestLine.startsWith("GET")) {
                    handleGetRequest(requestLine, writer);
                } else {
                    writer.write("HTTP/1.1 400 Bad Request\r\n\r\n");
                }
                writer.flush();
            } catch (IOException e) {
                System.out.println("Error: " + e.getMessage());
                break;
            }
        }
    }

    private static void handleGetRequest(String requestLine, BufferedWriter writer) throws IOException {
        String[] requestParts = requestLine.split(" ")[1].split("\\?");
        if (requestParts.length < 2) {
            writer.write("HTTP/1.1 400 Bad Request\r\n\r\n");
            return;
        }

        String[] queryParams = requestParts[1].split("&");
        String username = null, password = null;
        for (String param : queryParams) {
            String[] keyValue = param.split("=");
            if ("username".equals(keyValue[0])) {
                username = keyValue.length > 1 ? keyValue[1] : null;
            } else if ("password".equals(keyValue[0])) {
                password = keyValue.length > 1 ? keyValue[1] : null;
            }
        }

        if (username != null && password != null) {
            UserInfo userInfo = new UserInfo(username, password);
            writeObjectToFile(userInfo);
            writer.write("HTTP/1.1 200 OK\r\n\r\n用户注册成功!");
        } else {
            writer.write("HTTP/1.1 400 Bad Request\r\n\r\n未找到用户名或者密码");
        }
    }

    // 将用户信息对象序列化并写入文件
    private static void writeObjectToFile(UserInfo userInfo) throws IOException {
        try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("userinfos.ser", true))) {
            objectOutputStream.writeObject(userInfo);
        }
    }
}
